/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate;

import javax.ejb.Stateless;
import javax.ejb.LocalBean;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author Igor Kovb
 */
@Stateless
@LocalBean
public class UserDAO {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    ElementDAOClass<User> coreUserDAO;
    ElementDAOClass<UserRole> coreUserRoleDAO;
    @Deprecated
    private User guest = null;

    public UserDAO() {
        coreUserDAO = new ElementDAOClass<User>(User.class);
        coreUserRoleDAO = new ElementDAOClass<UserRole>(UserRole.class);
    }

    //-----------------------------------User DAO section
    public List<User> getAllUsers() {
        List<User> res = (List<User>) coreUserDAO.getAllElements();
        return res;
    }

    public User getUserByID(int pID) {
        User res = (User) coreUserDAO.getElementByID(pID);
        return res;
    }

    public boolean addAndSaveNewUser(User newUser) {
        return coreUserDAO.addElement(newUser);
    }

    public User createEmptyUser() {
        return new User();
    }

    public void deleteUser(User userToDelete) {
        coreUserDAO.deleteElement(userToDelete);
    }

    public void updateUser(User userToUpdate) {
        coreUserDAO.updateElement(userToUpdate);
    }

    public User getUser(String login, String password) {
        User res = null;
        Session session = null;

        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            // creating a query
            Query query = session.createQuery("from User where login = :login and password = MD5(:pass)");

            query.setParameter("login", login).setParameter("pass", password);

            List l = query.list();
            if (l.isEmpty()) {
                return res;
            }
            res = (User) l.get(0);
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return res;
    }

    //-----------------------------------UserRole DAO section
    public List<UserRole> getAllUserRoles() {
        List<UserRole> res = (List<UserRole>) coreUserRoleDAO.getAllElements();
        return res;
    }

    public UserRole getUserRoleByID(int pID) {
        UserRole res = (UserRole) coreUserRoleDAO.getElementByID(pID);
        return res;
    }

    public void addAndSaveNewUserRole(UserRole newUserRole) {
        coreUserRoleDAO.addElement(newUserRole);
    }

    public UserRole createEmptyUserRole() {
        return new UserRole();
    }

    public void deleteUserRole(UserRole userRoleToDelete) {
        coreUserRoleDAO.deleteElement(userRoleToDelete);
    }

    public void updateProduct(UserRole userRoleToUpdate) {
        coreUserRoleDAO.updateElement(userRoleToUpdate);
    }

    /**
     * @author SBelonozko
     * 
     * Возвращает Особого пользователя - Гостя. Это незарегестрированный пользователь.
     * @return guest user
     */
    @Deprecated
    public User getGuestUser() {
        if (guest == null) {
            guest = new User();
            guest.setLogin("Guest");
            guest.setFirstName("Гостюшка");
            guest.setLastName("Гостевич");
            guest.setEmail("Гость тчк Маил сабака ру");
            //guest.setId(1000000);
            guest.setPassword("нискажу");
            guest.setRole(getUserRoleByID(4));
        }

        return guest;
    }

    /**
     * @author SBelonozko
     * 
     * Возвращает первого попавшегося пользователя, у которого совпадает параметр login
     * @param login
     * @return
     * <b>NULLABE!!!</b>
     */
    public User getUserByLogin(String login) {
        User res = null;
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            // creating a query			
            Query query = session.createQuery("from User where login = :login");

            query.setParameter("login", login);

            List l = query.list();
            if (l.isEmpty()) {
                return res;
            }
            res = (User) l.get(0);

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return res;
    }
    /*
    public List<User> getAllManagers() {
    throw new UnsupportedOperationException("Not yet implemented");
    }
     */

    /**
     * 
     * @author SBelonozko
     * Возвращает список пользователей, имеющих заданный параметр.
     * 
     * @param role
     * @return Список пользователей
     * <b>NULLABE!!!</b>
     */
    public List<User> getUsersByRole(UserRole role) {
        if (role == null) {
            return null;
        }
        List<User> res = null;
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            // creating a query
            Query query = session.createQuery("from User where roleID=:roleid");

            query.setParameter("roleid", role.getId());

            res = query.list();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return res;
    }
}
